// vite.config.js
import { defineConfig } from 'vite';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import archiver from 'archiver';
import chokidar from 'chokidar';
import crypto from 'crypto';

// 获取当前文件的目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const pluginName = 'giteeai-translate';

function generateDevAppcast(outputPath) {
    const fileBuffer = fs.readFileSync(outputPath);
    const hashSum = crypto.createHash('sha256');
    hashSum.update(fileBuffer);
    const sha256 = hashSum.digest('hex');

    // 读取 info.json 获取版本号
    const infoPath = path.resolve(__dirname, 'src', 'info.json');
    const info = JSON.parse(fs.readFileSync(infoPath, 'utf8'));
    const version = info.version;

    // 使用绝对路径，确保文件名正确
    const relativePluginPath = path.relative(path.resolve(__dirname, 'dist/dev'), outputPath);

    return {
        identifier: "com.gitee.ai.bob-translate",
        versions: [
            {
                version: version,
                desc: "🛠️ 开发版本",
                sha256: sha256,
                url: `http://localhost:5173/${relativePluginPath}`,
                minBobVersion: "1.8.0"
            }
        ]
    };
}

function updateInfoJsonAppcast(isDev) {
    const infoPath = path.resolve(__dirname, 'src', 'info.json');
    const info = JSON.parse(fs.readFileSync(infoPath, 'utf8'));

    if (isDev) {
        // 总是添加新的开发时间戳
        const baseVersion = info.version.split('-dev.')[0];
        info.version = `${baseVersion}-dev.${Date.now()}`;
        info.appcast = 'http://localhost:5173/appcast.json';
    } else {
        // 移除开发版本标记，恢复原始版本
        info.version = info.version.split('-dev.')[0];
        info.appcast = 'https://gitee.com/normalcoder/bob-plugin-giteeai-translate/main/raw/appcast.json';
    }

    return info;
}

function createBobPlugin(isDev = false) {
    const outputDir = isDev ? 'dist/dev' : 'dist/build';
    const outputFileName = isDev ? `${pluginName}-dev.bobplugin` : `${pluginName}.bobplugin`;
    const outputPath = path.resolve(__dirname, outputDir, outputFileName);

    // 确保输出目录存在
    fs.mkdirSync(path.resolve(__dirname, outputDir), { recursive: true });

    // 创建插件归档
    const archive = archiver('zip', { zlib: { level: 9 } });
    const output = fs.createWriteStream(outputPath);

    archive.pipe(output);

    // 更新 info.json
    const updatedInfo = updateInfoJsonAppcast(isDev);
    const tempInfoPath = path.resolve(__dirname, 'src', 'info.json');

    // 使用原子写入，减少文件系统事件
    const tempFile = `${tempInfoPath}.tmp`;
    fs.writeFileSync(tempFile, JSON.stringify(updatedInfo, null, 4));
    fs.renameSync(tempFile, tempInfoPath);

    // 添加所有 src 目录文件到归档
    archive.directory('src/', false);

    return new Promise((resolve, reject) => {
        output.on('close', () => {
            console.log(`${outputFileName} created successfully in ${outputDir}`);

            // 仅在开发模式下生成本地 appcast
            if (isDev) {
                const devAppcast = generateDevAppcast(outputPath);
                const devAppcastPath = path.resolve(__dirname, outputDir, 'appcast.json');

                // 使用原子写入，减少文件系统事件
                const tempAppcastFile = `${devAppcastPath}.tmp`;
                fs.writeFileSync(tempAppcastFile, JSON.stringify(devAppcast, null, 4));
                fs.renameSync(tempAppcastFile, devAppcastPath);

                console.log(`Dev appcast created at ${devAppcastPath}`);
            }

            resolve();
        });

        archive.on('error', (err) => {
            reject(err);
        });

        archive.finalize();
    });
}

export default defineConfig({
    root: path.resolve(__dirname, 'dist/dev'),
    server: {
        port: 5173,
        open: false,
        cors: true,
    },
    build: {
        rollupOptions: {
            input: {
                main: path.resolve(__dirname, 'src/main.js')
            }
        }
    },
    plugins: [
        {
            name: 'bob-plugin-build',
            buildStart() {
                // 创建生产 .bobplugin
                return createBobPlugin(false);
            }
        }
    ]
});

export function watchPlugin() {
    const watcher = chokidar.watch('src', {
        persistent: true,
        ignoreInitial: false
    });

    watcher.on('all', async (event, path) => {
        console.log(`${event} detected in ${path}`);
        await createBobPlugin(true);
    });
}

export { createBobPlugin };